package com.lyy.weather.network;

import android.content.Context;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.lyy.weather.bean.ThreadFlag;
import com.lyy.weather.database.DataSolver;
import com.lyy.weather.database.DatabaHelper;
import com.lyy.weather.database.DatabaseUtil;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.LogRecord;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HttpUtil {//从网上接收数据的工具包

    private final int START=0;
   // private final int END=1;
   // private final int GO=2;
   // private final String MY_KEY="key=85a8b7a7d80a46ecac5b6255beaa96a6";
    private final String MY_KEY="key=71deef4fa8874cbfa2b058a9ea091f7d";

    private String location;
    private int requestType;
    private Context mContext;
    private DatabaHelper dbHelper;
    private ThreadFlag threadFlag;

    //构造方法，传入要查询的地点和类型
    public HttpUtil(String location,int requestType,Context mContext,DatabaHelper dbHelper) {
        this.location = location;
        this.requestType=requestType;
        this.mContext=mContext;
        this.dbHelper=dbHelper;

    }

    //在发送request之前判断要发送哪种Request
    public  static class  MyRequestType{
        public  static final int CITY_REQUEST=0;
        public static final int WEATHER_TIMELY_REQUEST=1;
        public static final int WEATHER_HOURLY_REQUEST=2;
        public static final int WEATEHR_WEEKLY_REQUEST=3;
        public  static final int LIFE_INDICES_REQUEST=4;
        public  static final int AIR_INDICES_REQUEST=5;
        public static final int ALL_DATA_REQUEST=6;

    };

   private static class MyUrl{
        //获取城市信息的url
        public static final String CITY_URL="https://geoapi.qweather.com/v2/city/lookup?";
        //获取实时天气的url
        public static final String WEATHER_TIMELY_URL="https://devapi.qweather.com/v7/weather/now?";
        //获取逐小时天气
        public static final String WEATHER_HOURLY_URL="https://devapi.qweather.com/v7/weather/24h?";
        //获取近七天天气
        public static final String WEATHER_WEEKLY_URL="https://devapi.qweather.com/v7/weather/7d?";
        //获取天气生活指数
        public static final String LIFE_INDICES_URL="https://devapi.qweather.com/v7/indices/1d?";
        //获取实时空气质量指数
        public static final String AIR_INDICES_URL="https://devapi.qweather.com/v7/air/now?";

    }

    //接收数据的方法
    //嵌套使用了getSpecificUrl方法用于获取Url
    private void sendRequestWithHttpURLConnection(int requestType,String location){
       if(requestType!=MyRequestType.ALL_DATA_REQUEST){
           //   new Thread(new Runnable() {
             //     @Override
               //   public void run() {
                      getData(requestType,location);
               //   }
           //   }).start();


       }else{

           getData(MyRequestType.WEATHER_HOURLY_REQUEST,location);
           getData(MyRequestType.WEATEHR_WEEKLY_REQUEST,location);
           getData(MyRequestType.WEATHER_TIMELY_REQUEST,location);
           getData(MyRequestType.LIFE_INDICES_REQUEST,location);
           getData(MyRequestType.AIR_INDICES_REQUEST,location);
       }


    }

    //获取特定的URL字符串
    //判断要接收那种类型数据，返回组装好的url字符串
    //小心location为空的情况
    private String getSpecificUrl(int requestType,String location){
        StringBuilder sb=new StringBuilder();
        switch (requestType){
            case MyRequestType.CITY_REQUEST:
                sb.append(MyUrl.CITY_URL+"location="+location+"&"+MY_KEY);
                return sb.toString();

            case MyRequestType.WEATHER_TIMELY_REQUEST:
                 sb.append(MyUrl.WEATHER_TIMELY_URL+"location="+location+"&"+MY_KEY);
                 return sb.toString();

            case MyRequestType.WEATHER_HOURLY_REQUEST:
                sb.append(MyUrl.WEATHER_HOURLY_URL+"location="+location+"&"+MY_KEY);
                return sb.toString();

            case MyRequestType.WEATEHR_WEEKLY_REQUEST:
                sb.append(MyUrl.WEATHER_WEEKLY_URL+"location="+location+"&"+MY_KEY);
                return sb.toString();

            case MyRequestType.LIFE_INDICES_REQUEST:
                sb.append(MyUrl.LIFE_INDICES_URL+"type=0&"+"location="+location+"&"+MY_KEY);
               // Log.d("TAG", sb.toString());
                return sb.toString();

            case MyRequestType.AIR_INDICES_REQUEST:
                sb.append(MyUrl.AIR_INDICES_URL+"location="+location+"&"+MY_KEY);
                return sb.toString();
            default:
                return null;
        }
    }

    public void getDataFromApi(){
       //除了城市以外，location都要是id的形式
       sendRequestWithHttpURLConnection(requestType,location);
    }

    //接收指定城市编号的相关数据，并添加到数据库中
    public void getAllDataOfSpecificLocation(){
              sendRequestWithHttpURLConnection(MyRequestType.WEATHER_HOURLY_REQUEST,location);
              sendRequestWithHttpURLConnection(MyRequestType.WEATEHR_WEEKLY_REQUEST,location);
              sendRequestWithHttpURLConnection(MyRequestType.WEATHER_TIMELY_REQUEST,location);
              sendRequestWithHttpURLConnection(MyRequestType.LIFE_INDICES_REQUEST,location);
              sendRequestWithHttpURLConnection(MyRequestType.AIR_INDICES_REQUEST,location);

    }

    private void getData(int requestType,String location){
        try {
            String urlStr=getSpecificUrl(requestType,location);

            if(urlStr!=null){
                URL url=new URL(urlStr);
                OkHttpClient client=new OkHttpClient();
                Request request=new Request.Builder()
                        .url(url)
                        .build();
                Response response=client.newCall(request).execute();
                if(response!=null)
                {
                    String responseData=response.body().string();
                    // Log.d("TAG", responseData);
                    //给数据进行处理
                    DataSolver dataSolver=new DataSolver(mContext,dbHelper);
                    dataSolver.solveResponseData(responseData,requestType,location);

                }else{
                    Log.d("TAG", "response获取失败，建议检查url是否有错误");
                }

            }else{
                Log.d("TAG", "url字符串获取失败，建议检查getSpecificUrl方法的参数是否有错误");
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
